from datetime import datetime

from flask_login import current_user, login_required

from ruoyi_flask.models.system.Test import Test
from ruoyi_flask.routes import main_routes
from ruoyi_flask.models import SysConfig
from flask import request, jsonify
from ruoyi_flask import db, cache
import flask_excel as excel
from ruoyi_flask.decorator import permission, dataScope


# 【请填写功能名称】对象 test
# @author djsoft
# @date 2025-02-05


@main_routes.route('/system/test/list', methods=['GET'])
@login_required
@permission('system:test:list')
# @dataScope('test.create_by')
def system_test_list(filters=[]):
    if 'num' in request.args:
        filters.append(Test.num == request.args['num'])
    page = request.args.get('pageNum', 1, type=int)
    rows = request.args.get('pageSize', 10, type=int)
    pagination = Test.query.filter(*filters).paginate(page=page, per_page=rows, error_out=False)
    test_list = pagination.items
    return jsonify({'msg': '操作成功', 'code': 200, 'rows': [test.to_json() for test in test_list], 'total': pagination.total})


@main_routes.route('/system/test/<id>', methods=['GET'])
@login_required
@permission('system:test:query')
def system_test_get_info(id):
    test = Test.query.get(id)
    return jsonify({'msg': '操作成功', 'code': 200, 'data': test.to_json()})


@main_routes.route('/system/test', methods=['POST'])
@login_required
@permission('system:test:add')
def system_test_add():
    test = Test()
    if 'num' in request.json: test.num = request.json['num']
    db.session.add(test)
    return jsonify({'code': 200, 'msg': '操作成功'})


@main_routes.route('/system/test', methods=['PUT'])
@login_required
@permission('system:test:edit')
def system_test_edit():
    test = Test.query.get(request.json['id'])
    if 'num' in request.json: test.num = request.json['num']
    db.session.add(test)
    return jsonify({'msg': '操作成功', 'code': 200})


@main_routes.route('/system/test/<string:ids>', methods=['DELETE'])
@login_required
@permission('system:test:remove')
def system_test_remove(ids):
    idList = ids.split(',')
    for id in idList:
        test = Test.query.get(id)
        if test:
            db.session.delete(test)
    return jsonify({'code': 200, 'msg': '操作成功'})


@main_routes.route('/system/test/export', methods=['POST'])
@login_required
@permission('system:test:export')
def system_test_export():
    rows = []
    rows.append(['', ''])
    tests = Test.query.all()
    for test in tests:
        row = []
        row.append(test.id)
        row.append(test.num)
        rows.append(row)
    return excel.make_response_from_array(rows, "xlsx", file_name="test")